<?php

namespace Modules\H5\Http\Controllers\Login;

use Illuminate\Http\Request;
use Modules\Common\Models\Texts;
use Modules\Common\Util\Api;


class login
{
    /**
     * pc端用户token验证
     * @Route(path=/api/verification method=post)
     */
    public function verification()
    {
        $id = request('id');
        $token = request('token');
        if ($id && $token) {
            return $this->updateTexts($id, $token);
        }
        if ($id && !$token) {
            return $this->getTexts($id);
        }    
    
        return $this->createTexts();
    }
    
    /**
     * 查询标识
     */
    private function getTexts($id)
    {
        $texts = Texts::where('id', $id)->first();
        if (!$texts) {
            return Api::fail('记录不存在', 404);
        }
        return Api::success($texts);
    }
    
    /**
     * 更新标识
     */
    private function updateTexts($id, $token)
    {
        $texts = Texts::where('id', $id)->first();
        if (!$texts) {
            return null;
        }
        $data = Texts::where('id',$id)->update(['token'=>$token,'updated_at'=>date('Y-m-d H:i:s')]);
        if ($data) {
            return Api::success($data);
        }
        return null;
    }
    
    /**
     * 创建标识
     */
    private function createTexts()
    {
        $unique_key = $this->generateUuid();
        $texts = new Texts();
        $texts->unique_key = $unique_key;
        $texts->created_at = now();
        $texts->save();
        return Api::success($texts);
    }
        
    function generateUuid() {
        $data = random_bytes(16);
        $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // version 4
        $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // variant 1
        return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
    }
}